import 'dart:math';

import 'package:flutter/material.dart';
import 'package:mi_mang_flutter/provider/mimang_app_theme.dart';
import 'package:mi_mang_flutter/utils/shared_preferences.dart';
import 'package:mi_mang_flutter/utils/toast_util.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:provider/provider.dart';

class ThemeProvider with ChangeNotifier {
  /// 夜间模式
  static const _APPDARKMODE = "ThemeAppDarkMode";

  /// 主题色
  static const _APPTHEMECOLOR = "ThemeAppThemeColor";

  /// 当前字体
  static const _APPFONT = "ThemeAppFont";

  /// 当前比例系数
  static const _APPTEXTSCALEFACTOR = "AppTextScaleFactor";

  /// 定义字体名称(与yaml文件中对应)
  static const fontValueList = [
    'system',
    'xingkai',
    'chenmeizi',
    'kuaile',
  ];

  /// 当前字体索引
  int? _fontIndex;

  /// 当前字体缩放比例(默认1.0)
  double? _textScaleFactor;

  int? get fontIndex => _fontIndex;

  double? get textScaleFactor => _textScaleFactor;

  MaterialColor? get themeColor => _themeColor;

  /// 用户选择的明暗模式
  bool? _userDarkMode;

  /// 当前主题颜色
  MaterialColor? _themeColor;

  ThemeProvider() {
    /// 用户选择的明暗模式
    _userDarkMode = SpUtil.getBool(_APPDARKMODE, defValue: false);

    /// 获取主题色
    _themeColor = Colors.primaries[SpUtil.getInt(_APPTHEMECOLOR, defValue: 5)];

    /// 获取字体
    _fontIndex = SpUtil.getInt(_APPFONT, defValue: 0);

    /// 获取字体缩放比例
    _textScaleFactor = SpUtil.getDouble(_APPTEXTSCALEFACTOR, defValue: 1.0);
  }

  /// 根据索引获取字体名称,这里牵涉到国际化
  static String fontName(index, context) {
    switch (index) {
      case 0:
        return "跟随系统";
      case 1:
        return "手写字体";
      case 2:
        return "优雅字体";
      case 3:
        return "快乐字体";
      default:
        return '';
    }
  }

  /// 切换字体
  switchFont(int? index) {
    _fontIndex = index;
    switchTheme();
    saveFontIndex(index);
  }

  /// 字体选择持久化
  static saveFontIndex(int? index) async {
    await SpUtil.putInt(_APPFONT, index);
  }

  final botToastBuilder = BotToastInit();

  /// 过渡建设者
  /// 主界面构建前,整体添加的构建步骤;
  /// 该处用来处理文本字体大小不随系统字体大小改变;
  TransitionBuilder buildMediaQuery() {
    return (context, child) {
      // 或者 MediaQueryData.fromWindow(WidgetsBinding.instance.window).copyWith(textScaleFactor: 1.0),
      // 保证文字大小不受手机系统设置影响 https://www.kikt.top/posts/flutter/layout/dynamic-text/
      return MediaQuery(
        data: MediaQuery.of(context).copyWith(
          textScaler: TextScaler.linear(_textScaleFactor ?? 1.0),
        ),
        child: botToastBuilder(context, child),
      );
    };
  }

  /// 切换字体比例因子(放大缩小字体)
  switchTextScaleFactor(double textScaleFactor) {
    _textScaleFactor = textScaleFactor;
    notifyListeners();
    saveTextScaleFactor(textScaleFactor);
  }

  /// 字体大小比例
  static saveTextScaleFactor(double textScaleFactor) async {
    await SpUtil.putDouble(_APPTEXTSCALEFACTOR, textScaleFactor);
  }

  /// 切换指定色彩
  ///
  /// 没有传[brightness]就不改变brightness,color同理
  void switchTheme({bool? userDarkMode, MaterialColor? color}) {
    _userDarkMode = userDarkMode ?? _userDarkMode;
    _themeColor = color ?? _themeColor;
    notifyListeners();
    saveThemeToStorage(_userDarkMode, _themeColor!);
  }

  /// 随机一个主题色彩
  ///
  /// 可以指定明暗模式,不指定则保持不变
  void switchRandomTheme({Brightness? brightness}) {
    int colorIndex = Random().nextInt(Colors.primaries.length - 1);
    switchTheme(
      userDarkMode: Random().nextBool(),
      color: Colors.primaries[colorIndex],
    );
  }

  /// 根据主题 明暗 和 颜色 生成对应的主题
  /// [dark]系统的Dark Mode
  themeData({bool platformDarkMode = false}) {
    var isDark = platformDarkMode || _userDarkMode!;
    var themeData = MiMangAppTheme.customeThemeData(
      isDark,
      themeColor,
      fontValueList[_fontIndex!],
    );
    return themeData;
  }

  /// 保存主题信息到Sp
  ///
  /// [userDarkMode] 是否夜间模式
  ///
  /// [themeColor] 当前主题色
  saveThemeToStorage(bool? userDarkMode, MaterialColor themeColor) async {
    var index = Colors.primaries.indexOf(themeColor);
    SpUtil.putBool(_APPDARKMODE, userDarkMode);
    SpUtil.putInt(_APPTHEMECOLOR, index);
  }

  static void switchDarkMode(BuildContext context) {
    if (MediaQuery.of(context).platformBrightness == Brightness.dark) {
      Toast.showInfo("检测到系统为暗黑模式,已为你自动切换");
    } else {
      Provider.of<ThemeProvider>(context, listen: false).switchTheme(
          userDarkMode: Theme.of(context).brightness == Brightness.light);
    }
  }
}
